﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using log4net.Config;
using System.Web;
using System.IO;
using log4net.Core;

namespace Base.Utils.Logging
{
    public class Log4NetAdapter : ILogger
    {
        private readonly ILog _log;
        private readonly Dictionary<string, Level> _logLevels;

        public Log4NetAdapter()
        {
            var log4NetPath =  HttpContext.Current.Server.MapPath("~/Configs/log4net.config");
            //Configure Log4net
            FileInfo fi = new FileInfo(log4NetPath);
            if (fi != null && fi.Exists)
                XmlConfigurator.Configure(fi);     

            _log = LogManager.GetLogger(Base.Utils.AppSettings.Instance.logger_name);
            _logLevels = new Dictionary<string, Level>
                             {
                                 {LogType.Debug.ToString(), Level.Debug},
                                 {LogType.Error.ToString(), Level.Error},
                                 {LogType.Info.ToString(), Level.Info},
                                 {LogType.Warn.ToString(), Level.Warn},
                                 {LogType.Fatal.ToString(), Level.Fatal}
                             };

        }

        #region ILogger Members

        public void Log(string message, LogType logType)
        {
            //Create a LoggingEvent using the information required to show in the log file 
            //and pass it to Log() which actually writes it in the file
            var loggingEvent = new LoggingEvent(
                typeof(Log4NetAdapter),
                _log.Logger.Repository,
                _log.Logger.Name,
                _logLevels[logType.ToString()],
                message,
                null);
            _log.Logger.Log(loggingEvent);
        }
        public void Log(string message, Exception exception, LogType logType)
        {
            //Create a LoggingEvent using the information required to show in the log file 
            //and pass it to Log() which actually writes it in the file
            var loggingEvent = new LoggingEvent(
               typeof(Log4NetAdapter),
               _log.Logger.Repository,
               _log.Logger.Name,
               _logLevels[logType.ToString()],
               exception.Message,
               exception);
            _log.Logger.Log(loggingEvent);
        }
       

        #endregion
    }
}
